import { memo, useEffect, useState, useMemo } from 'react'
import { Tree } from 'antd'
import { FileTextOutlined, HomeOutlined, BookOutlined, TableOutlined } from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { searchDocList } from '@/views/DocList/pages/list/api'
import { getKnowledgeBaseDirectoryByUserId } from '@/views/KnowledgeBase/pages/list/api'
import { getExcelContentsByUserId } from '@/apis/excel'
import styles from './index.module.less'

/**
 * 侧边栏菜单组件 - 支持文档中心和知识库的三层树形结构
 * 
 * 功能特性：
 * - 文档中心：二层结构（文档中心 -> 具体文档）
 * - 知识库：三层结构（知识库 -> 知识库名称 -> 具体文档）
 * - 表格中心：二层结构（表格中心 -> 具体表格）
 * - 智能路由同步：根据当前URL自动选中和展开对应节点
 * - 按需展开：默认收起，用户手动或路由自动展开
 */
const MenuList = () => {
    const navigate = useNavigate()
    const location = useLocation()
    
    // 数据状态
    const [docList, setDocList] = useState([])
    const [knowledgeBaseList, setKnowledgeBaseList] = useState([])
    const [excelList, setExcelList] = useState([])
    // 树形控件状态
    const [expandedKeys, setExpandedKeys] = useState([])
    const [selectedKeys, setSelectedKeys] = useState([])
    
    // 并行获取所有菜单数据
    useEffect(() => {
        const fetchData = async () => {
            try {
                const userId = localStorage.getItem('userId')
                const [docRes, kbRes, excelRes] = await Promise.all([
                    searchDocList(),
                    getKnowledgeBaseDirectoryByUserId(),
                    getExcelContentsByUserId(userId)
                ])
                
                docRes?.code === 200 && setDocList(docRes.data || [])
                kbRes?.code === 200 && setKnowledgeBaseList(kbRes.data || [])
                excelRes?.code === 200 && setExcelList(excelRes.data || [])
            } catch (error) {
                console.error('获取菜单数据失败:', error)
            }
        }
        fetchData()
    }, [])
    
    // 根据URL路径同步选中状态和展开状态
    useEffect(() => {
        const pathParts = location.pathname.split('/').filter(Boolean)
        const [, segment1, segment2] = pathParts
        
        // 文档中心路由处理
        if (location.pathname.includes('/docList')) {
            if (segment2 === 'docDetail') {
                setSelectedKeys([`doc-${pathParts[2]}`])
                setExpandedKeys(prev => [...new Set([...prev, 'doc-center'])])
            } else {
                setSelectedKeys(['doc-center'])
            }
            return
        }
        
        // 知识库路由处理
        if (location.pathname.includes('/knowledgeBase')) {
            if (pathParts.length >= 3) {
                const isDocDetail = segment2 === 'docDetail'
                const key = isDocDetail ? `kb-${segment1}` : `kb-doc-${segment1}-${segment2}`
                const expandKeys = isDocDetail 
                    ? ['knowledge-base'] 
                    : ['knowledge-base', `kb-${segment1}`]
                
                setSelectedKeys([key])
                setExpandedKeys(prev => [...new Set([...prev, ...expandKeys])])
            } else if (pathParts.length === 2) {
                setSelectedKeys([`kb-${segment1}`])
                setExpandedKeys(prev => [...new Set([...prev, 'knowledge-base'])])
            } else {
                setSelectedKeys(['knowledge-base'])
            }
            return
        }
        
        // 默认首页
        setSelectedKeys(['home'])
    }, [location.pathname])
    
    // 构建树形数据结构
    const treeData = useMemo(() => [
        {
            title: '首页',
            key: 'home',
            icon: <HomeOutlined />
        },
        {
            title: '文档中心',
            key: 'doc-center',
            icon: <FileTextOutlined />,
            children: docList.map(item => ({
                title: item.docName,
                key: `doc-${item.docId}`,
                icon: <FileTextOutlined />,
                isLeaf: true
            }))
        },
        {
            title: '知识库',
            key: 'knowledge-base',
            icon: <BookOutlined />,
            children: knowledgeBaseList.map(kb => ({
                title: kb.knowledgeBaseName,
                key: `kb-${kb.knowledgeBaseId}`,
                icon: <BookOutlined />,
                children: kb.docDirectory?.map(doc => ({
                    title: doc.docName,
                    key: `kb-doc-${kb.knowledgeBaseId}-${doc.docId}`,
                    icon: <FileTextOutlined />,
                    isLeaf: true
                })) || []
            }))
        },
        {
            title: '表格中心',
            key: 'excel-center',
            icon: <TableOutlined />,
            children: excelList.map(item => ({
                title: item.title,
                key: `excel-${item.id}`,
                icon: <TableOutlined />,
                isLeaf: true
            }))
        }
    ], [docList, knowledgeBaseList, excelList])

    // 节点选择处理 - 统一的路由跳转逻辑
    const handleSelect = (selectedKeys) => {
        const key = selectedKeys[0]
        if (!key) return
        
        // 路由映射配置
        const routes = {
            'home': '/',
            'doc-center': '/docList',
            'knowledge-base': '/knowledgeBase',
            'excel-center': '/excelList'
        }
        
        // 直接路由跳转
        if (routes[key]) {
            navigate(routes[key])
        }
        // 文档中心文档跳转
        else if (key.startsWith('doc-')) {
            navigate(`/docList/docDetail/${key.slice(4)}`)
        }
        // 知识库文档跳转
        else if (key.startsWith('kb-doc-')) {
            const [kbId, docId] = key.slice(7).split('-')
            navigate(`/knowledgeBase/${kbId}/${docId}`)
        }
        // 知识库详情跳转
        else if (key.startsWith('kb-')) {
            navigate(`/knowledgeBase/${key.slice(3)}/docDetail`)
        }
        // 表格中心表格跳转
        else if (key.startsWith('excel-')) {
            navigate(`/excelList/excelDetail/${key.slice(6)}`)
        }
        setSelectedKeys(selectedKeys)
    }



    return (
        <div className={styles.menuContainer}>
            <Tree
                showIcon
                blockNode
                selectedKeys={selectedKeys}
                expandedKeys={expandedKeys}
                onSelect={handleSelect}
                onExpand={setExpandedKeys}
                treeData={treeData}
                style={{
                    background: 'transparent',
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
                }}
            />
        </div>
    )
}

export const MemoMenu = memo(MenuList)